package sharetime.core.pager;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class DefaultPager implements Pager {
	@SuppressWarnings("unchecked")
	private List page;

	@SuppressWarnings("unchecked")
	private Iterator iter;

	private int index;

	@SuppressWarnings("unchecked")
	public DefaultPager() {
		this(((Collection) (Collections.EMPTY_LIST)));
	}

	@SuppressWarnings("unchecked")
	public DefaultPager(Collection col) {
		if (col == null)
			page = Collections.EMPTY_LIST;
		else if (page instanceof List)
			page = (List) col;
		else
			page = new ArrayList(col);
		iter = page.iterator();
	}

	public boolean isEmpty() {
		if (page == null)
			return true;
		else
			return page.isEmpty();
	}

	@SuppressWarnings("unchecked")
	public Iterator iterator() {
		return iter;
	}

	@SuppressWarnings("unchecked")
	public List getCurrentPage() {
		return page;
	}

	public void nextPage() {
	}

	public boolean onLastPage() {
		return true;
	}

	public void skipTo(int index) throws PagerException {
		if (index < 0)
			throw new PagerException("Cannot skipTo a negative amount ["
					+ index + "]");
		int originalIndex = this.index;
		int distance = 0;
		if (index > page.size()) {
			distance = page.size();
			this.index = page.size();
		} else {
			distance = index - this.index;
			this.index = index;
		}
		for (int i = originalIndex; i < distance; i++)
			iter.next();

	}

	public int getIndex() {
		return index;
	}

	public int getIndexOfFirstItemInCurrentPage() {
		return 0;
	}

	public void remove() {
		throw new UnsupportedOperationException(
				"This iterator does not support removal");
	}

	public boolean hasNext() {
		return iter.hasNext();
	}

	public Object next() {
		Object o = iter.next();
		index++;
		return o;
	}

}
